package bill_service

import (
	"encoding/json"
	"fmt"

	"github.com/EDDYCJY/go-gin-example/models"
)

// Login 定义登录请求结构体
type AddBill struct {
	BillList string
}
type BillMsg struct {
	OutOrderSn  string  `json:"out_order_sn"`
	ExpressNo   string  `json:"express_no"`
	ExpressName string  `json:"express_name"`
	Weight      float64 `json:"weight"`
	Freight     float64 `json:"freight"`
	GoodsID     int     `json:"goods_id"`
}

func (t *AddBill) AddBill() (map[string]interface{}, error) {

	// 解析 JSON 响应
	var result BillMsg
	if err := json.Unmarshal([]byte(t.BillList), &result); err != nil {
		return nil, fmt.Errorf("failed to unmarshal response: %v", err)
	}
	var maps = map[string]interface{}{
		"goods_id": result.GoodsID,
	}
	goodsInfo, _ := models.GetGoodsInfo([]string{"streamer_id", "institution_id", "goods_id", "selling_price", "supply_price"}, maps)
	if goodsInfo.GoodsID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	maps = map[string]interface{}{
		"goods_id":     result.GoodsID,
		"out_order_sn": result.OutOrderSn,
	}
	billInfo, _ := models.GetBillInfo([]string{"bill_id"}, maps)
	if billInfo.BillID != 0 {
		return nil, fmt.Errorf("订单已存在")
	}

	var install = map[string]interface{}{
		"streamer_id":    goodsInfo.StreamerId,    // 主播ID
		"out_order_sn":   result.OutOrderSn,       // 线上订单号
		"express_no":     result.ExpressNo,        // 快递单号
		"express_name":   result.ExpressName,      // 快递名称
		"weight":         result.Weight,           // 订单重量
		"freight":        result.Freight,          // 运费
		"institution_id": goodsInfo.InstitutionId, // 机构ID
		"goods_id":       result.GoodsID,          // 商品ID
		"selling_price":  goodsInfo.SellingPrice,  // 卖货价
		"supply_price":   goodsInfo.SupplyPrice,   // 供应价
	}
	res, _ := models.AddBill(install)
	if res == 0 {
		return nil, fmt.Errorf("添加商品失败")
	}
	return nil, nil
}
